package com.zjhb.common.util;  
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
//前后端分离token验证，跨域外网可访问
public class TokenUtil {
	// 自定义验证key
	private final static String API_KEY = "zhangjian";
	// 过期时间
	private final static long ttlMillis = 360000 * 1000;

	public static String createJWT(JwtUser user) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(API_KEY);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		Map<String, Object> map = new HashMap<>();
		BeanCopy.copyBean2Map(map, user);		
		JwtBuilder builder = Jwts.builder().setClaims(map).setIssuer("test").setIssuedAt(now)
				.signWith(signatureAlgorithm, signingKey);
		if (ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}

		return builder.compact();
	}
//public static void main(String[] args) {
//	JwtUser user=new JwtUser();
//	user.setId("432432");
//	user.setDepartId("423423");
//	user.setName("张剑");
//	String token=TokenUtil.createJWT(user);
//	parseJWT(token);
//}
	public static JwtUser parseJWT(String jwt) {
		JwtUser jwtUser = new JwtUser();
		try {
			Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(API_KEY))
					.parseClaimsJws(jwt).getBody();
			BeanCopy.copyBean2Bean(jwtUser, claims);
			jwtUser.setCode(true);
			return jwtUser;
		} catch (Exception e) {
			e.printStackTrace();
			jwtUser.setCode(false);
			return jwtUser;
		}

	}
}  